package org.elepower.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.elepower.dao.FunctionDao;
import org.elepower.dao.UserDao;
import org.elepower.pojo.PsFunction;
import org.elepower.pojo.PsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/elepower")
public class LoginController {

    @Autowired
    private FunctionDao functionDao;
    @Autowired
    private UserDao userDao;

    @RequestMapping("/success")
    @ResponseBody
    public  Map<String,Object> success(HttpSession session) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        PsUser user = (PsUser) SecurityUtils.getSubject().getPrincipal();
        session.setAttribute(Constants.LOGIN_USER,user);
        //保存用户权限
        List<PsFunction> list = functionDao.getPerByUserId(user.getId());
        session.setAttribute(Constants.LOGIN_USER_PERS,list);
        //更新用户最后一次登录时间
        user.setLastLoginTime(new Date());
        userDao.updateLastTime(user);
        return map;
    }

    @RequestMapping("/index")
    public String index() throws Exception{
        return "main";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login() throws Exception{
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request) throws Exception{
        Map<String,Object> map = new HashMap<>();
        String exceptionName = request.getAttribute("shiroLoginFailure").toString();
        if (exceptionName.equals(UnknownAccountException.class.getName())){
            map.put("code",1);
            map.put("msg","用户名不正确");
            return map;
        }else if(exceptionName.equals(IncorrectCredentialsException.class.getName())){
            map.put("code",2);
            map.put("msg","密码不正确");
            return map;
        }else if(exceptionName.equals(LockedAccountException.class.getName())){
            map.put("code",3);
            map.put("msg","用户被冻结!");
            return map;
        }else{
            map.put("code",4);
            map.put("msg","请填写用户名或密码!");
        }
        return map;
    }



}
